package com.atguigu.service.impl;

import com.atguigu.entity.SkuImage;
import com.atguigu.entity.SkuInfo;
import com.atguigu.entity.SkuPlatformPropertyValue;
import com.atguigu.entity.SkuSalePropertyValue;
import com.atguigu.mapper.SkuInfoMapper;
import com.atguigu.service.SkuImageService;
import com.atguigu.service.SkuInfoService;
import com.atguigu.service.SkuPlatformPropertyValueService;
import com.atguigu.service.SkuSalePropertyValueService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 库存单元表 服务实现类
 * </p>
 *
 * @author GuoJH
 * @since 2021-08-25
 */
@Service
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo> implements SkuInfoService {
    @Autowired
    private SkuPlatformPropertyValueService skuPlatformPropertyService;
    @Autowired
    private SkuSalePropertyValueService skuSalePropertyService;
    @Autowired
    private SkuImageService skuImageService;
    //保存单个sku信息
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        baseMapper.insert(skuInfo);
        //获取sku的id  共用
        Long skuInfoId = skuInfo.getId();
        //获取平台属性集合 为其sku赋值skuId
        List<SkuPlatformPropertyValue> skuPlatformPropertyList = skuInfo.getSkuPlatformPropertyValueList();
        if (!CollectionUtils.isEmpty(skuPlatformPropertyList)){
            for (SkuPlatformPropertyValue skuPlatformProperty : skuPlatformPropertyList) {
                skuPlatformProperty.setSkuId(skuInfoId);
            }
            //批量添加平台属性值
            skuPlatformPropertyService.saveBatch(skuPlatformPropertyList);
        }
        //获取商品属性集合  赋skuId值和商品spu的id值
        List<SkuSalePropertyValue> skuSalePropertyList = skuInfo.getSkuSalePropertyValueList();
        if (!CollectionUtils.isEmpty(skuSalePropertyList)){
            for (SkuSalePropertyValue skuSaleProperty : skuSalePropertyList) {
                skuSaleProperty.setSkuId(skuInfoId);
                skuSaleProperty.setProductId(skuInfo.getProductId());
            }
            //批量添加
            skuSalePropertyService.saveBatch(skuSalePropertyList);
        }
        //获取图片集合 赋skuId值
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)){
            for (SkuImage skuImage : skuImageList) {
                skuImage.setSkuId(skuInfoId);
            }
            skuImageService.saveBatch(skuImageList);
        }

    }
    //分页查询skuInfo信息
    @Override
    public void querySkuInfoByPage(Page<SkuInfo> page) {
        QueryWrapper<SkuInfo> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        baseMapper.selectPage(page,wrapper);
    }
}
